//
//  BaseMapView.m
//  FMDB
//
//  Created by aha on 2023/6/16.
//
#import "BaseMapView.h"
#import <AMapSearchKit/AMapSearchKit.h>
#import "BasePointAnnotation.h"
#import "BaseAnnotationView.h"
#import "MANaviRoute.h"
#import "CommonUtility.h"
#import "JetourLinePlugin.h"
@interface BaseMapView()<MAMapViewDelegate,AMapSearchDelegate>
@property(nonatomic,strong)MAMapView *mapView;
@property(nonatomic,strong)MAPolyline *polyline;//折线
@property(nonatomic,strong)AMapSearchAPI *searchApi;//驾车线路规划
@property(nonatomic,strong)AMapDrivingCalRouteSearchRequest *request;//驾车线路规划
@property (strong, nonatomic) MANaviRoute * naviRoute;  //用于显示当前路线方案.
@property (strong, nonatomic) AMapRoute *route;  //路径规划信息
@end

@implementation BaseMapView
- (AMapDrivingCalRouteSearchRequest *)request{
    if(_request == nil){
        _request = [[AMapDrivingCalRouteSearchRequest alloc] init];
        _request.strategy = 32;
        _request.showFieldType = AMapDrivingRouteShowFieldTypeCost|AMapDrivingRouteShowFieldTypeTmcs|AMapDrivingRouteShowFieldTypeNavi|AMapDrivingRouteShowFieldTypeCities|AMapDrivingRouteShowFieldTypePolyline;
    }return _request;
}

- (instancetype)initWithMsg:(id)msg
{
    self = [super init];
    if (self) {
        [MAMapView updatePrivacyShow:AMapPrivacyShowStatusDidShow privacyInfo:AMapPrivacyInfoStatusDidContain];
        [MAMapView updatePrivacyAgree:AMapPrivacyAgreeStatusDidAgree];
     
        ///地图需要v4.5.0及以上版本才必须要打开此选项（v4.5.0以下版本，需要手动配置info.plist）
        [AMapServices sharedServices].enableHTTPS = YES;
        ///初始化地图
        self.backgroundColor = [UIColor grayColor];
        self.mapView = [[MAMapView alloc] initWithFrame:self.bounds];
        self.mapView.delegate = self;
           ///把地图添加至view
        [self addSubview:self.mapView];
        [self addMarkers:msg];
        __weak typeof(self) wself = self;
        [JetourLinePlugin setCallback:^(id obj) {
            [wself addMarkers:obj];
        }];
        
    }
    return self;
}

//添加markers
- (void)addMarkers:(id)obj{
    [self.mapView removeAnnotations:self.mapView.annotations];
    [self.mapView removeOverlays:self.mapView.overlays];
    if([obj isKindOfClass:[NSArray class]]){
        NSArray *list = (NSArray*)obj;
        _coordCount = list.count;
        _coords = (CLLocationCoordinate2D*)malloc(_coordCount * sizeof(CLLocationCoordinate2D));
        NSMutableArray *aMapGeoPoints = [NSMutableArray array];//途经点
        NSMutableArray *annotations = [NSMutableArray array];
        for (int i = 0;i<list.count;i++) {
            NSDictionary *dic = list[i];
            BasePointAnnotation *pointAnnotation = [[BasePointAnnotation alloc] init];
            NSString *latStr =  [NSString stringWithFormat:@"%.6f",[[dic objectForKey:@"lat"] doubleValue]];
            NSString *lngStr =  [NSString stringWithFormat:@"%.6f",[[dic objectForKey:@"lng"] doubleValue]];
            double lat =  [latStr doubleValue];            double lng =  [lngStr doubleValue];
            pointAnnotation.dic = dic;
//            pointAnnotation.coordinate = CLLocationCoordinate2DMake(39.90960456049752, 116.3972282409668);
            pointAnnotation.coordinate = CLLocationCoordinate2DMake(lat, lng);
            [annotations addObject:pointAnnotation];
            _coords[i] = pointAnnotation.coordinate;//折现
            
            if(i == 0){
                self.request.origin =  [AMapGeoPoint locationWithLatitude:lat longitude:lng];
            }else if(i == list.count-1){
                self.request.destination =  [AMapGeoPoint locationWithLatitude:lat longitude:lng];
            }else{
                [aMapGeoPoints addObject: [AMapGeoPoint locationWithLatitude:lat longitude:lng]];
            }
        }
        
        [self.mapView addAnnotations:annotations];
        self.request.waypoints = aMapGeoPoints;
        [self searchDriver];
        
    }
}
//绘制折线
- (void)addLine{
    //构造折线对象
    self.polyline = [MAPolyline polylineWithCoordinates:_coords count:_coordCount];

    //在地图上添加折线对象
    [_mapView addOverlay: self.polyline];
    NSMutableArray *arr = [NSMutableArray array];
    [arr addObject:self.polyline];
    [self.mapView showAnnotations:self.mapView.annotations edgePadding:UIEdgeInsetsMake(20, 20, 20, 20) animated:NO];
    
    
//    [self.mapView setVisibleMapRect:[CommonUtility mapRectForOverlays:self.naviRoute.routePolylines]
//                        edgePadding:UIEdgeInsetsMake(20, 20, 20, 20)
//                           animated:false];

}
//线路规划
- (void)searchDriver{
    if(self.searchApi == nil){
        self.searchApi = [[AMapSearchAPI alloc] init];
        self.searchApi.delegate = self;
    }
//    self.request = [[AMapDrivingCalRouteSearchRequest alloc] init];
//    self.request.origin =  [AMapGeoPoint locationWithLatitude:39.910267 longitude:116.370888];
//    self.request.destination =  [AMapGeoPoint locationWithLatitude:39.989872 longitude:116.370888];
//
//    self.request.strategy = 5;
//    [self.searchApi AMapDrivingV2RouteSearch:self.request];
     
    
    [self.searchApi AMapDrivingV2RouteSearch:self.request];
    
}


//marker view
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *reuseIndetifier = @"annotationReuseIndetifier";
        BaseAnnotationView *annotationView = (BaseAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndetifier];
        if (annotationView == nil)
        {
            annotationView = [[BaseAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIndetifier];
        }
        BasePointAnnotation *tion = (BasePointAnnotation*)annotation;
        //设置中心点偏移，使得标注底部中间点成为经纬度对应点
        annotationView.dic = tion.dic;
        annotationView.centerOffset = CGPointMake(0, -18);
        return annotationView;
    }
    return nil;
}
//折线
- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id <MAOverlay>)overlay{
    if ([overlay isKindOfClass:[MAPolyline class]])
        {
            MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:overlay];
            
            polylineRenderer.lineWidth    = 3.f;
            polylineRenderer.strokeColor  = [UIColor colorWithRed:0/255.0 green:161/255.0 blue:152/255.0 alpha:255/255.0];
            polylineRenderer.lineJoinType = kMALineJoinRound;
            polylineRenderer.lineCapType  = kMALineCapRound;
            
            return polylineRenderer;
        }
        return nil;
}

/* 路径规划搜索回调. */
- (void)onRouteSearchDone:(AMapRouteSearchBaseRequest *)request response:(AMapRouteSearchResponse *)response{
    if (response.route == nil)
    {
        [self addLine];
        return;
    }
    self.route = response.route;
    [self presentCurrentRouteCourse];
//    /* 缩放地图使其适应polylines的展示. */
//    [self.mapView setVisibleMapRect:[CommonUtility mapRectForOverlays:self.naviRoute.routePolylines]
//                        edgePadding:UIEdgeInsetsMake(RoutePlanningPaddingEdge, RoutePlanningPaddingEdge, RoutePlanningPaddingEdge, RoutePlanningPaddingEdge)
//                           animated:YES];
    
   //解析response获取路径信息，具体解析见 Demo
}


//在地图上显示当前选择的路径
- (void)presentCurrentRouteCourse {
    [self.naviRoute removeFromMapView];  //清空地图上已有的路线
        MANaviAnnotationType type = MANaviAnnotationTypeDrive;
        self.naviRoute = [MANaviRoute naviRouteForPath:self.route.paths[0] withNaviType:type showTraffic:YES startPoint:nil endPoint:nil];
        [self.naviRoute addToMapView:self.mapView];
        
        /* 缩放地图使其适应polylines的展示. */
        [self.mapView setVisibleMapRect:[CommonUtility mapRectForOverlays:self.naviRoute.routePolylines]
                            edgePadding:UIEdgeInsetsMake(20, 20, 20, 20)
                               animated:false];
}



/* 路径规划搜索失败 */
- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error
{
    [self addLine];
}

- (void)dealloc{
    int i = 0;
}
@end
